package com.fg.util;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import javax.imageio.ImageIO;




public class ModifyImage {
	private BufferedImage buffer;
	
	public ModifyImage(File file) throws IOException{
		buffer = ImageIO.read(file);
	}
	
	public ModifyImage(URL url) throws IOException{
		buffer = ImageIO.read(url);
	}
	
	public ModifyImage(InputStream stream) throws IOException{
		buffer = ImageIO.read(stream);
	}
	
	public ModifyImage(BufferedImage buffer){
		this.buffer = buffer;
	}
	
	public ModifyImage resize(int width, int height){
		BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = dest.createGraphics();
		g.setComposite(AlphaComposite.Src);
		g.drawImage(buffer, 0, 0, width, height, null);
		g.dispose();
		
		return new ModifyImage(dest);
	}
	
	/**
	 * 세로 가로중 길이가 큰 쪽을 size크기에 맞춰 비율을 바꾼다. 
	 * @param size
	 * @return
	 */
	public ModifyImage resize(int size){
		if(buffer.getWidth() >= buffer.getHeight()){
			int resizedHeight = (size*buffer.getHeight()/buffer.getWidth());
			return resize(size, resizedHeight);
		}else{
			int resizedWidth = (size*buffer.getWidth()/buffer.getHeight());
			return resize(resizedWidth, size);
		}
		
		
	}
	
	public ModifyImage crop(int x, int y, int width, int height){
		if(buffer.getHeight()>55){
			BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D g = dest.createGraphics();
			g.setComposite(AlphaComposite.Src);
			g.drawImage(buffer, 0, 0, width, height, x, y, x+width, y+height, null);
			g.dispose();
			
			return new ModifyImage(dest);
		}
		return new ModifyImage(buffer);		
	}
	
	public void writeTo(File tumbnailFile, String formatName) throws IOException{
		ImageIO.write(buffer, formatName, tumbnailFile);
	}
	
	public boolean isSupportedImageFormat(){
		return buffer != null ? true : false;
	}
	
	public int getWidth(){
		return buffer.getWidth();
	}
	public int getHeigh(){
		return buffer.getHeight();
	}
	
	
}
